package cz.pproproj.aaservice.ddbmodule;

import cz.pproproj.aaservice.ddbmodule.dbaccess.DBUserDAO;
import cz.pproproj.aaservice.ddbmodule.dbaccess.DBUsersManagement;
import cz.pproproj.aaservice.guimodule.model.AuthenticationException;
import cz.pproproj.aaservice.aasbllmodule.authentication.AuthenticationUser;
import cz.pproproj.aaservice.aasbllmodule.authentication.AuthenticationDataAccess;

import java.util.List;

/**
 * @author David
 * @since 17. 1. 2015
 */
public class DBAuthenticationDataAccessImpl implements AuthenticationDataAccess {

    private final String _configurationDirName;

    private final DBUsersManagement _dbUsersManagement;

    public DBAuthenticationDataAccessImpl(String configurationDirName) {
        _configurationDirName = configurationDirName;
        String configFile = "/dbconfigurations/" + _configurationDirName + "/dbModuleConfig.xml";
        _dbUsersManagement = DataDBModuleImpl.getInstance().getDbUsersManagement(configFile);
        boolean found = false;//todo for testing only remove after testing is over
        for (AuthenticationUser dbUserDAO :_dbUsersManagement.getAllUsers()) {
            if (dbUserDAO.getUserName().equals("admin")) {
                found = true;
            }
        }
        if (!found) {
            _dbUsersManagement.addUser(new AuthenticationUser("admin", "pass"));
        }
    }

    @Override
    public boolean authenticate(AuthenticationUser user) throws AuthenticationException {
        return _dbUsersManagement.authenticate(user);
    }

    @Override
    public String addUser(AuthenticationUser user) throws AuthenticationException {
        return _dbUsersManagement.addUser(user);
    }

    @Override
    public void deleteUser(AuthenticationUser user) throws AuthenticationException {
        _dbUsersManagement.deleteUser(user);
    }

    @Override
    public String getConfigurationDirName() {
        return _configurationDirName;
    }

    @Override
    public List<AuthenticationUser> getAllUsers() {
        return _dbUsersManagement.getAllUsers();
    }
}
